package in.muton.edushare.components.alertpanel.api;

import in.muton.edushare.EduShareSession;
import in.muton.edushare.processing.objects.ObjectTypeId;
import in.muton.edushare.wicket.models.CayenneList;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.apache.wicket.model.IModel;

import com.edushare.common.dao.PollsDAO;
import com.edushare.common.dao.UserPollDAO;
import com.edushare.common.vo.DateComparision;
import com.edushare.common.vo.Poll;
import com.edushare.common.vo.UserPoll;
import com.edushare.common.vo.Users;

public class PollAlertMgr {
	public PollAlertMgr(IModel<Users> userModel) {
		this.userModel = userModel;
	}

	public List<DateComparision> getPolls() {
		Users u = (Users) userModel.getObject();
		List<UserPoll> pL = u.getRequestedPolls();
		List<DateComparision> pSorted = new ArrayList<DateComparision>();
		for (UserPoll p : pL) {
			if (p.getDate().getTime() > new Date().getTime()) {
				pSorted.add(p);
			}
		}

		Collections.sort(pSorted);
		return pSorted;
	}

	public static List<DateComparision> getPolls(int creatorType, int creatorId) {
		List<Poll> dc = new PollsDAO(EduShareSession.get()
				.getSessionORMInterface()).getPollsByCreator(creatorType,
				creatorId);

		List<DateComparision> pSorted = new ArrayList<DateComparision>();
		for (Poll p : dc) {
			if (p.getDate().getTime() > new Date().getTime()
					&& p.getStatus() != Poll.POLL_STATUS_CLOSED
					&& p.getStatus() != Poll.POLL_STATUS_DRAFT) {
				Users u = EduShareSession.get().getLoggedInUser();
				CayenneList<Users> owners = ObjectTypeId.getOwner(creatorId,
						creatorType);
				if (owners.contains(u)) {
					pSorted.add(p);
				} else {
					List<Users> ul = new UserPollDAO(EduShareSession.get()
							.getSessionORMInterface()).getPollRespondents(p);
					if(ul.contains(u))
						pSorted.add(p);
				}
			}
		}
		Collections.sort(pSorted);
		return pSorted;
	}

	private IModel<Users> userModel;
}
